#!/bin/env python3
import sys
import configparser
import pyrp
import os
if "config" in sys.argv:
    parser = configparser.ConfigParser()
    parser.add_section("deuf")
    try:
        server = input("请输入frp服务器地址:")
    except:
        print('请输入frp服务器地址，没有请自建\n建好服务器后重新执行“./deuf.py config”以便配置')
        exit(100)
    if server == "":
        print('请输入frp服务器地址，没有请自建\n建好服务器后重新执行“./deuf.py config”以便配置')
        exit(100)
    else:
        parser.set("deuf", "server", server)
    try:
        port = input("请输入frp服务器端口:")
    except:
        port = 7000
    if port == "":
        port = 7000
    parser.set("deuf", "port", str(port))
    with open("config.ini", "w+") as c:
        parser.write(c)
else:
    cfg = configparser.ConfigParser()
    cfg.read("config.ini")
    if len(sys.argv) > 1:
        name = sys.argv[1]
    else:
        name = input('请输入名称(任意):')
    print(f'名称:{name}')
    if "f" in sys.argv:
        print('模式:性能模式')
        mode = "xtcp"
    else:
        print('模式:兼容模式')
        mode = "stcp"
    sk = pyrp.m()
    print(f'密码:{sk}')
    print('您无需记录密码，只需要保存好这对defu镜像即可')
    print('正在生成服务端配置文件')
    parser = configparser.ConfigParser()
    parser.add_section("common")
    parser.set("common", "server_addr", cfg.get("deuf","server"))
    parser.set("common", "server_port", cfg.get("deuf","port"))
    parser.add_section(f'{name}_server')
    parser.set(f'{name}_server', "type", mode)
    parser.set(f'{name}_server', "sk", sk)
    parser.set(f'{name}_server', "plugin", "unix_domain_socket")
    parser.set(f'{name}_server', "plugin_unix_path", "/var/run/docker.sock")
    with open("./build-t/frpc.ini", "w+") as c:
        parser.write(c)
    print('正在构建服务端')
    os.system(f'docker build --pull --rm -f "build-t/dockerfile" -t daze456/deuf:{name}_server "build-t"')
    os.system(f'docker save daze456/deuf:{name}_server>{name}_server.tar')
    print('正在生成客户端配置文件')
    parser.remove_section(f'{name}_server')
    parser.add_section(f'{name}_client')
    parser.set(f'{name}_client', "type", mode)
    parser.set(f'{name}_client', "role", "visitor")
    parser.set(f'{name}_client', "server_name", f'{name}_server')
    parser.set(f'{name}_client', "sk", sk)
    parser.set(f'{name}_client', "bind_addr", "0.0.0.0")
    parser.set(f'{name}_client', "bind_port", "80")
    with open("./build-t/frpc.ini", "w+") as c:
        parser.write(c)
    print('正在构建客户端')
    os.system(f'docker build --pull --rm -f "build-t/dockerfile" -t daze456/deuf:{name}_client "build-t"')
    os.system(f'docker save daze456/deuf:{name}_client>{name}_client.tar')